<?php

namespace app\modules\pay\controllers;

use app\common\controllers\CorsController;
use app\components\response\Response;
use app\config\Constants;
use app\modules\pay\services\MerchantService;
use app\modules\pay\services\PaymentLogService;
use app\modules\pay\utils\SignUtil;
use app\utils\QueueUtil;
use yii\base\UserException;

class NotifyController extends CorsController{

    //支付通知
    public function actionPayNotify(){
        \Yii::$app->getResponse()->format = Response::FORMAT_HTML;

        $data = \Yii::$app->getRequest()->post();
        if(empty($data)){
            throw new UserException("数据为空");
        }
        $log = PaymentLogService::getInfoByPlatformOrderNo($data['out_trade_no']);
        if(!$log){
            throw new UserException("订单不存在");
        }
        //是否已经处理
        if($log->pay_status == Constants::PAY_STATUS_SUCCESS){
            return "SUCCESS";
        }
        //验证签名
        if(!SignUtil::verify($data,MerchantService::getPaymentById($log->goodsOrder->merchant_id)->getConfig()['sign_key'])){
            throw new UserException("签名验证失败");
        }

        //更新订单
        if(!PaymentLogService::successStatus($data)){
            throw new UserException("订单更新失败");
        }
        //下单消息
        QueueUtil::fanout(Constants::MSG_TYPE_ORDER,Constants::ORDER_WAIT,['order_no'=>$log->goodsOrder->order_no]);

        return "SUCCESS";
    }

    //退款通知
    public function actionRefundNotify(){
        \Yii::$app->getResponse()->format = Response::FORMAT_HTML;

        $data = \Yii::$app->getRequest()->post();
        if(empty($data)){
            throw new UserException("数据为空");
        }
        $log = PaymentLogService::getInfoByPlatformOrderNo($data['out_trade_no']);
        if(!$log){
            throw new UserException("订单不存在");
        }
        //是否已经处理
        if($log->pay_status == Constants::PAY_STATUS_REFUND){
            return "SUCCESS";
        }
        //验证签名
        if(!SignUtil::verify($data,MerchantService::getPaymentById($log->goodsOrder->merchant_id)->getConfig()['sign_key'])){
            throw new UserException("签名验证失败");
        }
        //更新订单
        if(!PaymentLogService::refundStatus($data)){
            throw new UserException("订单更新失败");
        }

        return "SUCCESS";
    }
}